/**
 * 检查app版本是否需要升级
 */
import {
	updateApp
} from '@/api/customApi.js'

const compareVersions = (version1, version2) => {
	const v1 = version1.split('.');
	const v2 = version2.split('.');
	for (let i = 0; i < Math.max(v1.length, v2.length); i++) {
		const num1 = parseInt(v1[i] || 0);
		const num2 = parseInt(v2[i] || 0);
		if (num1 < num2) {
			return -1; // 第一版本号小于第二版本号
		}
		if (num1 > num2) {
			return 1; // 第一版本号大于第二版本号
		}
	}
	return 0; // 相等
}

//获取当前页面url
const getCurrentPageRoute = () => {
	let currentRoute;
	let pages = getCurrentPages() // 获取栈实例
	if (pages && pages.length) {
		currentRoute = pages[pages.length - 1].route;
	}
	return currentRoute
}

const checkVersion = async () => {
	const selfVersion = uni.getSystemInfoSync().appWgtVersion; //当前App版本号
	const {
		versionShort,
		installUrl
	} = await updateApp()
	//线上版本号高于当前，进行在线升级
	if (compareVersions(selfVersion, versionShort) === -1) {
		let platform = uni.getSystemInfoSync().platform //手机平台
		//安卓手机弹窗升级
		if (platform === 'android') {
			//当前页面不是升级页面跳转防止多次打开
			if (getCurrentPageRoute() !== 'pages/upgrade/upgrade') {
				uni.navigateTo({
					url: '/pages/upgrade/upgrade',
					success() {
						uni.$emit('upgrade-app', {
							installUrl,
							versionShort
						})
					}
				})
			}
		}
		//IOS
		else {}
	}
}
export default checkVersion